package org.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.RetrySleeper;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

public class CuratorListen {

    public static void main(String[] args) {
        //重试策略，初始时间为6s，重试次数为2次
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(6000, 2);

        CuratorFramework build = CuratorFrameworkFactory.builder()
                .connectString("10.10.10.92:2181").sessionTimeoutMs(9000)
                .retryPolicy(retryPolicy).build();
        //开启链接
        build.start();
        //建立节点 支持多级目录同事创建，指定节点类型
        try {
              //创建缓存节点
            final NodeCache nodeCache = new NodeCache(build, "/lockg",false);
            nodeCache.start(true);
            nodeCache.getListenable().addListener(new NodeCacheListener() {
                public void nodeChanged() throws Exception {
                    System.err.println("节点::"+nodeCache.getCurrentData().getPath());
                    System.err.println("数据::"+nodeCache.getCurrentData().getData());
                }
            });

         build.create().forPath("/lockg","tahs".getBytes());
           Thread.sleep(1000000000);
          build.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
